package com.dd.common.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.common.entity.SysMenu;
import com.dd.common.entity.SysRole;
import com.dd.common.entity.SysRoleMenu;
import com.dd.common.mapper.SysMenuMapper;
import com.dd.common.mapper.SysRoleMapper;
import com.dd.common.service.SysRoleMenuService;
import com.dd.common.service.SysRoleService;
import com.dd.common.utils.ListUtils;
import com.dd.common.vo.MenuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author cheng
* @description 针对表【c_sys_role(角色表)】的数据库操作Service实现
* @createDate 2025-08-23 17:00:07
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
    implements SysRoleService{
    @Resource
    private SysRoleMenuService sysRoleMenuService;

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<?> getRoleMenu(Long roleId) {
        List<SysMenu> menuList = sysMenuMapper.selectList(new LambdaQueryWrapper<>(SysMenu.class)
                .inSql(roleId != null, SysMenu::getId, "select menu_id from c_sys_role_menu where role_id =" + roleId)
        );
        List<MenuVO> menuVOList = menuList.stream().map(menu -> {
            MenuVO menuVO = new MenuVO();
            BeanUtils.copyProperties(menu, menuVO);
            return menuVO;
        }).collect(Collectors.toList());
        return ListUtils.listToTree(JSON.parseArray(JSON.toJSONString(menuVOList)), "id", "parentId", "children");
    }

    @Override
    @Transactional
    public Boolean assignMenu(Long roleId, List<Long> menuIds) {
        // 删除角色原有的菜单权限
        LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId, roleId);
        sysRoleMenuService.remove(wrapper);

        // 如果没有新菜单，直接返回 true（清空成功）
        if (CollectionUtils.isEmpty(menuIds)) {
            return true;
        }

        // 构造新的关联数据
        List<SysRoleMenu> roleMenuList = menuIds.stream()
                .map(menuId -> {
                    SysRoleMenu rm = new SysRoleMenu();
                    rm.setRoleId(roleId);
                    rm.setMenuId(menuId);
                    return rm;
                })
                .collect(Collectors.toList());

        // 批量插入新的菜单权限
        return sysRoleMenuService.saveBatch(roleMenuList);
    }
}




